package protocol

import (
	"encoding/binary"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/core/server"
	"gitee.com/crack007/udp-penetrate/src/common/constant"
	"net"
)

type HeartbeatProtocol struct {
	Finish uint32 // 0-请求，1-响应，不需要再处理
	Body   string
}

func NewHeartbeatProtocol() *HeartbeatProtocol {
	return &HeartbeatProtocol{}
}

func (p *HeartbeatProtocol) Code() uint32 {
	return constant.CMD_HEARTBEAT
}

func (p *HeartbeatProtocol) Process(session *server.Session, clientConn *net.UDPConn) IProtocol {
	if p.Finish == 1 {
		goose.GetLogger().Debug("heartbeat req-> %s", p.Body)
		return nil
	}
	heartbeatProtocol := NewHeartbeatProtocol()
	heartbeatProtocol.Finish = 1
	heartbeatProtocol.Body = "heartbeat resp-> " + p.Body
	return heartbeatProtocol
}

func (p *HeartbeatProtocol) Marshall() []byte {
	var body = make([]byte, 4)
	binary.BigEndian.PutUint32(body, p.Finish)
	body = append(body, []byte(p.Body)...)
	return body
}

func (p *HeartbeatProtocol) UnMarshall(data []byte) {
	p.Finish = binary.BigEndian.Uint32(data)
	p.Body = string(data[4:])
}
